package com.yzmoney.wechat.service;

import com.yzmoney.common.constant.Constants;
import com.yzmoney.common.constant.PropertyUtils;
import com.yzmoney.common.model.JsonResult;
import com.yzmoney.common.util.HttpClientUtils;
import com.yzmoney.common.util.JsonUtils;
import com.yzmoney.wechat.model.general.GeneralReturnCode;
import com.yzmoney.wechat.model.send.TemplateMsg;
import com.yzmoney.wechat.model.send.TextMsg;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 发送客服消息/模板消息
 *
 * @author DOVE
 */
@Component
public class WechatSendMsgService {
    private static Logger logger = Logger.getLogger(WechatSendMsgService.class);

    private static String baseSendMsgURL = PropertyUtils.getValue("SENDMSG_URL", "", Constants.GZH_PATH);

    private static String baseSendTmpMsgURL = PropertyUtils.getValue("TMLMSGSEND_URL", "", Constants.GZH_PATH);

    private static String baseQYHSendMsgURL = PropertyUtils.getValue("SENDMSG_URL", "", Constants.QYH_PATH);

    private static String baseQYHSendTmpMsgURL = PropertyUtils.getValue("TMLMSGSEND_URL", "", Constants.QYH_PATH);

    @Autowired
    private WechatAccessTokenService wechatAccessTokenService;

    public WechatSendMsgService() {
        super();
    }

    /**
     * 发送文本消息
     *
     * @param openId
     * @param content
     * @return
     */
    public boolean sendTextMsg(String openId, String content) {
        TextMsg textMsg = new TextMsg(openId, content, null);
        String accessToken = wechatAccessTokenService.getGZHAccessToken();
        String url = getSendMsgUrl(accessToken);
        if (StringUtils.isEmpty(url)) {
            return false;
        }
        String result = HttpClientUtils.post(url, JsonUtils.toJson(textMsg));
        GeneralReturnCode generalReturnCode = JsonUtils.toObject(result, GeneralReturnCode.class);

        logger.info(Constants.LOGPRIFIX + "textMsg=" + textMsg.toString() + ",accessToken=" + accessToken + ",generalReturnCode=" + generalReturnCode.toString());

        if (generalReturnCode.getErrcode().equals("0")) {
            return true;
        } else {
            return false;
        }
    }

    public synchronized boolean sendTextMsg(long threadId, String openId, String content) {
        TextMsg textMsg = new TextMsg(openId, content, null);
        String accessToken = wechatAccessTokenService.getGZHAccessToken();
        String url = getSendMsgUrl(accessToken);
        if (StringUtils.isEmpty(url)) {
            return false;
        }
        String result = HttpClientUtils.post(url, JsonUtils.toJson(textMsg));
        GeneralReturnCode generalReturnCode = JsonUtils.toObject(result, GeneralReturnCode.class);

        logger.info(Constants.LOGPRIFIX + "textMsg=" + textMsg.toString() + ",accessToken=" + accessToken + ",generalReturnCode=" + generalReturnCode.toString());

        if (generalReturnCode.getErrcode().equals("0")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 发送模板消息
     *
     * @param templateMsg
     * @return
     */
    public boolean sendTemplateMsg(TemplateMsg templateMsg) {
        String accessToken = wechatAccessTokenService.getGZHAccessToken();

        String url = getSendTmpMsgUrl(accessToken);
        if (StringUtils.isEmpty(url)) {
            return false;
        }
        String result = HttpClientUtils.post(url, JsonUtils.toJson(templateMsg));
        GeneralReturnCode generalReturnCode = JsonUtils.toObject(result, GeneralReturnCode.class);
        logger.info(Constants.LOGPRIFIX + "accessToken=" + accessToken + ",generalReturnCode=" + generalReturnCode.toString());

        if (generalReturnCode.getErrcode().equals("0")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 发送模板消息（建议用这种方式，此时模板对象属于通用类型）
     *
     * @param templateMsg(模板消息 json string)
     * @return
     */
    public JsonResult sendTemplateMsg(String templateMsg, String type) {
        String accessToken = null;
        String url = null;
        JsonResult jsonResult = new JsonResult();
        if (type.equals("gzh")) {
            accessToken = wechatAccessTokenService.getGZHAccessToken();
            url = getSendTmpMsgUrl(accessToken);
        } else if (type.equals("qyh")) {
            accessToken = wechatAccessTokenService.getQYHAccessToken();
            url = getSendQYHTmpMsgUrl(accessToken);
        }
        if (StringUtils.isEmpty(url)) {
            jsonResult.setCode(Constants.CODE_FAILURE);
            jsonResult.setMsg("请求发送模版地址为空，请联系管理员");

            return jsonResult;
        }
        String result = HttpClientUtils.post(url, templateMsg);
        logger.info(Constants.LOGPRIFIX+"send msg result:"+result);
        GeneralReturnCode generalReturnCode = JsonUtils.toObject(result, GeneralReturnCode.class);
        logger.info(Constants.LOGPRIFIX + "accessToken=" + accessToken + ",generalReturnCode=" + generalReturnCode.toString());

        if (generalReturnCode.getErrcode().equals("0")) {
            jsonResult.setCode(Constants.CODE_SUCCESS);

        } else {
            jsonResult.setCode(Constants.CODE_FAILURE);
            jsonResult.setMsg(generalReturnCode.getErrmsg());
        }
        return jsonResult;
    }

    /**
     * 拼接公众号 OAuth2.0请求地址
     *
     * @return
     */
    private static String getSendMsgUrl(String access_Token) {
        if (StringUtils.isEmpty(access_Token)) {
            return null;
        }
        String sendMsgUrl = baseSendMsgURL + access_Token;
        return sendMsgUrl;
    }

    /**
     * 拼接公众号 OAuth2.0请求地址
     *
     * @return
     */
    private static String getSendQYHMsgUrl(String access_Token) {
        if (StringUtils.isEmpty(access_Token)) {
            return null;
        }
        String sendMsgUrl = baseQYHSendMsgURL + "?access_token=" + access_Token;
        return sendMsgUrl;
    }


    /**
     * 拼接公众号 OAuth2.0请求地址
     *
     * @return
     */
    private static String getSendTmpMsgUrl(String access_Token) {
        if (StringUtils.isEmpty(access_Token)) {
            return null;
        }
        String sendTmpMsgUrl = baseSendTmpMsgURL + "?access_token=" + access_Token;
        return sendTmpMsgUrl;
    }

    private static String getSendQYHTmpMsgUrl(String access_Token) {
        if (StringUtils.isEmpty(access_Token)) {
            return null;
        }
        String sendTmpMsgUrl = baseQYHSendTmpMsgURL + "?access_token=" + access_Token;
        return sendTmpMsgUrl;
    }
}
